# coding=utf-8
import hashlib
import random

from oss.oss_api import *


class AliyunOSS(object):
    def __init__(self, bucket="laoyaoguai"):
        # 判断是否使用内网地址
        # self.data_center = "oss-cn-shanghai.aliyuncs.com"
        self.data_center = "img.laoyaoguai.com.cn"
        self.app_id = "LTAIuq5bWKzLxV38"
        self.app_secret = "pwX4uX7F6ocxcDWnd8XsqsbKS3gsCo"
        self.oss = OssAPI(self.data_center, self.app_id, self.app_secret)
        self.bucket = bucket
        self.image_bucket_domain = ""

    def upload_pic(self, path, file_content):
        # 文件名随机化
        file_name = hashlib.md5(str(int(time.time() * 1000000)) + file_content.name.encode("utf-8")).hexdigest() + \
                    os.path.splitext(file_content.name)[-1]

        if hasattr(file_content, 'chunks'):
            file_content = ''.join(chunk for chunk in file_content.chunks())
        f = StringIO.StringIO(file_content)

        # path开头结尾没有'/' 例如 restaurant/1/images
        ret = self.oss.put_object_from_fp(bucket=self.bucket,
                                          object=path + file_name, fp=f)
        if ret.status / 100 == 2:
            return "/" + path + file_name

    def get_image(self, path, expire_time=30):
        # 获取图片和获取普通文件的方法不一样 阿里云文档有误 这里是自己去重新写了那个签名算法
        expire_time = str(int(time.time()) + expire_time)
        str_to_encrypt = "GET" + "\n" + "" + "\n" + "" + "\n" + expire_time + "\n" + "" + "/" + self.bucket + path
        s = hmac.new(self.app_secret, str_to_encrypt, hashlib.sha1)
        signature = base64.encodestring(s.digest()).strip()
        return "http://" + self.image_bucket_domain + path + "?OSSAccessKeyId=" + self.app_id + "&Expires=" + \
               expire_time + "&Signature=" + urllib.quote_plus(signature)

    def put_string(self, path, string):
        # path开头结尾没有'/' 例如 restaurant/1/images
        random_file_name = hashlib.md5(
            str(int(time.time())) + "".join(random.sample(['1', '2', '3', '4', '5'], 3))).hexdigest() + ".html"
        r = self.oss.put_object_from_string(self.bucket, path + "/" + random_file_name, string)
        return "/" + path + "/" + random_file_name

    def get_file_content(self, path):
        return self.oss.get_object(self.bucket, path).read(1024 * 1024 * 10)

    def delete_image(self, path, expire_time=30):

        return self.oss.delete_object(self.bucket, path).status
